import { defineStore } from 'pinia'
import { CheckoutInfo, UserAddress } from '@/types/checkout'
import { ApiRes } from '@/types/data'
import request from '@/utils/request'
// import { UserAddress } from "@/types/checkout";

export default defineStore({
  id: 'checkout',
  state: () => {
    return {
      checkoutInfo: {} as CheckoutInfo
    }
  },
  actions: {
    async getCheckoutInfo() {
      const res = await request.get<ApiRes<CheckoutInfo>>('/member/order/pre')
      this.checkoutInfo = res.data.result
    },
    // async addAddress(address: UserAddress) {
    //   const res = await request.post('/member/address', address)
    //   // 添加完地址，重新渲染
    //   this.getCheckoutInfo()
    // },

    // 新增地址
    async addAddress (address: UserAddress) {
      await request.post('/member/address', address)
      // 添加完地址，重新渲染
      this.getCheckoutInfo()
    },
    // 修改地址
    async updateAddress (address: UserAddress) {
      await request.put(`/member/address/${address.id}`, address)
      // 修改完地址，重新渲染
      this.getCheckoutInfo()
    }


  },
  getters: {
    showAddress(): UserAddress | null {
      // 判断是否请求到用户收货地址
      if (!this.checkoutInfo.userAddresses) return null

      if (this.checkoutInfo.userAddresses?.length === 0) {
        return null
      }

      // 如果有地址，找默认地址
      const defaultAddress = this.checkoutInfo.userAddresses?.find((item) => {
        item.isDefault === 0
      })

      if (defaultAddress) {
        return defaultAddress
      } else {
        return this.checkoutInfo.userAddresses[0]
      }
    }
  }
})